package com.monster.completable.future;

import com.monster.threadpool.MyThreadPool;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * description:
 * supplyAsync系列方法实现有返回值的异步计算，当需要异步执行一个任务，并且需要任务的执行结果时可以使用该系列方法
 * @author Yuanml on 2021/9/19 14:57
 */
public class SupplyAsync {
    public void studySupplyAsync() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("over");
            return "hello supply async";
        });
        System.out.println(future.get());
    }

    public void studySupplyAsyncWithCustomThreadPool() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("over");
            return "hello supply async";
        }, MyThreadPool.getThreadPool());
        System.out.println(future.get());
    }
}
